import React, { useState, useEffect } from 'react';
import BT_ICON from "@/assets/icons/backtop.png";
import { BackTop } from 'antd';
import './style.scss';

const ScrollToTopButton = () => {
    const [showButton, setShowButton] = useState(false);

    const handleScroll = () => {
        const distance = window.pageYOffset;
        const offsetToShowButton = 200; // 滚动超过 200px 后显示按钮
        setShowButton(distance > offsetToShowButton);
    };

    useEffect(() => {
        
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
       
    }, []);

    const handleBackTop = () => {
        // 将页面滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    return (
        <>
            <BackTop>
                <div
                    className={`custom-backtop-icon ${showButton ? 'show' : ''}`}
                    onClick={handleBackTop}
                >
                    <img className={"backtop"} src={BT_ICON} />
                </div>
            </BackTop>
        </>
    );
};

export default ScrollToTopButton;